package com.tencent.tbds.demo.hdfs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.security.UserGroupInformation;

/**
 *
 * tbds准备 Keytab 凭证参考TBDS使用手册
 *
 * usage:
 *
 *
 *
 * hadoop jar dev-demo-5.3.0.0.jar com.tencent.tbds.demo.hdfs.HDFSKerberosDemo --principal liulv/tbds.instance@TBDS-F6FE11XH --keytab /tmp/liulv.keytab
 *
 * hadoop jar dev-demo-5.3.0.0.jar com.tencent.tbds.demo.hdfs.HDFSKerberosDemo --principal hdfs-tdw@TBDS-F6FE11XH --keytab /etc/security/keytabs/hdfs.headless.keytab
 */
public class HDFSKerberosDemo {
    public static void main(String[] args) throws Exception {
        HDFSKerberosDemoOption option = new HDFSKerberosDemoOption(args);
        if (option.hasHelp()) {
            option.printHelp();
            return;
        }

        Configuration conf = new Configuration();

        //登录 Kerberos 账号
        System.setProperty("java.security.krb5.conf", "/etc/krb5.conf");
        Configuration configuration = new Configuration();
        configuration.set("hadoop.security.authentication" , "Kerberos" );
        UserGroupInformation. setConfiguration(configuration);
        //UserGroupInformation.loginUserFromKeytab("liulv/tbds.instance@TBDS-F6FE11XH", "/tmp/liulv.keytab");
        UserGroupInformation.loginUserFromKeytab(option.getPrincipal(), option.getKeytab());

        // 将配置强制设置为程序运行时的环境配置
        UserGroupInformation.setConfiguration(conf);
        UserGroupInformation.loginUserFromSubject(null);

        FileSystem fs = FileSystem.get(conf);

        FileStatus[] fileList = fs.listStatus(new Path("/user/liulv/") );
        System.out.println("---------------List all dirs and files under root dir---------------");
        for (FileStatus fileStatus : fileList) {
            System.out.println(fileStatus.toString());
        }
    }
}
